<template>
  <div>
    <form-template
      ref="form"
      :dialog-pending="dialogPending"
      :form-options="formOptions"
      @save="onSave"
    ></form-template>
  </div>
</template>

<script lang="ts">
import { Component, Emit } from 'vue-property-decorator'
import FormTemplate from '@/components/FormTemplate/index.vue'
import BaseForm from '@/models/baseForm'
import { IForm, FormType, Type, FormItem, FormOptions } from '@/models/form'
import { initFormOptions } from './FormOptions'
import { isNotEmpty } from '@/utils/validate'
import { createRole, updateRole, getRole } from '@/api/role'

@Component({ components: { FormTemplate } })
export default class CreateItem extends BaseForm implements IForm {
  public formOptions: FormOptions = initFormOptions()
  public id!: number

  open(type: Type, id: number) {
    this.formOptions = initFormOptions()
    this.id = id
    this.formOptions.type = type
    ;(this.$refs.form as any).open()
    if (type === Type.Edit || type === Type.View) {
      this.findById()
    }
  }

  async findById() {
    try {
      this.dialogPending = true
      const resp: any = await getRole(this.id)
      this.formOptions.formItems.forEach((item: FormItem) => {
        item.value = resp.data[item.key]
      })
    } finally {
      this.dialogPending = false
    }
  }

  async onSave(formData: any) {
    try {
      this.dialogPending = true
      if (this.formOptions.type === Type.Create) {
        const resp = await createRole(formData)
        this.$message.success('创建成功')
        this.onChange()
      } else if (this.formOptions.type === Type.Edit) {
        const resp = await updateRole(this.id, formData)
        this.$message.success('修改成功')
        this.onChange()
      }
      (this.$refs.form as any).close()
    } finally {
      this.dialogPending = false
    }
  }

  @Emit()
  onChange() {}
}
</script>

<style lang="scss" scoped></style>
